﻿/// <reference name="MicrosoftAjax.debug.js" />
/// <reference path="AjaxAction.js" />


	var grid;
	var caretaker;
	var keyboardHandler;
    
    var $model_main;    	
    
    var $fieldOptions = new Object();
    $fieldOptions.status = [
	    {
		    text:"Taken",
		    value:1
	    },
	    {
		    text:"Waiting",
		    value:2
	    },
	    {
		    text:"Blocked",
		    value:3		    
	    },
	    {
		    text:"Completed",
		    value:4
	    },
	    {
		    text:"Postponed",
		    value:5
	    }
    ];
    
    var $schema_main = [
	    {
		    headerText:"Id",
		    propertyName:"Moniker",
		    type:"number",
		    className:"id"
	    },
	    {
		    headerText:"Title",
		    propertyName:"Title",
		    type:"string",
		    className:"title"
	    },
	    {
		    headerText:"Notes",
		    propertyName:"Notes",
		    type:"string",
		    textMode:"multiline",
		    editable:true,
		    className:"notes"
	    },
	    {
		    headerText:"Status",
		    propertyName:"Status",
		    type:"number",
		    editable:true,
		    options:$fieldOptions.status,
		    validation:DataGrid.Validation.REQUIRED,
		    className:"status"
	    },
	    {
		    headerText:"Priority",
		    propertyName:"Priority",
		    type:"number",		
		    className:"priority"
	    },
	    {
		    headerText:"Weight",
		    propertyName:"Weight",
		    type:"number",
		    className:"weight"
	    }
    ];
    
	Event.observe(window, "load", init, false);
	
	function init() {
	            
		// keyboard
		keyboardHandler = new KeyboardHandler();
		keyboardHandler.addHandler("z", KeyboardHandler.Keys.ALT, undo.bindAsEventListener(this));
		keyboardHandler.addHandler("z", KeyboardHandler.Keys.ALT | KeyboardHandler.Keys.SHIFT, redo.bindAsEventListener(this));
		keyboardHandler.addHandler("y", KeyboardHandler.Keys.ALT, redo.bindAsEventListener(this));
		// caretaker
		caretaker = new CommandCaretaker();
		caretaker.onChange = caretaker_onChange;
		caretaker.onRedo = caretaker_onUndoRedo;
		caretaker.onUndo = caretaker_onUndoRedo;

        createGrid();
		bindGrid();
	}
	
	function createGrid() {
	    grid = new DataGrid();		
		Event.observe(grid, "row_edit_commit", this.gridEditCommit.bindAsEventListener(this));
		Event.observe(grid, "row_command", this.gridCommand.bindAsEventListener(this));
		Event.observe(grid, "row_created", this.gridRowRendered.bindAsEventListener(this));
	}
	function bindGrid() {
	    var options = {url: $getUrl};
        Sys.UI.DomElement.removeCssClass($get("progressBar"), "off");
	    new HttpHelper.AjaxAction().invoke(options, null, onGetCompleted);
	}
	
	function onGetCompleted(executor, eventArgs) {
        Sys.UI.DomElement.addCssClass($get("progressBar"), "off");
        if (executor.get_responseAvailable() && executor.get_statusCode() === 200)
        {
            $model_main = executor.get_object();    
            grid.initialize($('grid'), $schema_main, $model_main, true);		        
        } 
        if (executor.get_statusCode() === 500) {
            alert(executor.get_responseData());
        }        
    }

    function refresh() {        
        bindGrid();
    }
    
    function saveRequests() {
        var options = {url: $postUrl, format: 'json'};
        Sys.UI.DomElement.removeCssClass($get("progressBar"), "off");  
        var changeset = [];
        for (var i=0; i<$model_main.length; i++) {
            if($model_main[i].changed) {
                changeset.push($model_main[i]);
            }
        }
        var data = Sys.Serialization.JavaScriptSerializer.serialize(changeset);      
	    new HttpHelper.AjaxAction().invoke(options, data, onPostCompleted);        
    }
    
    function deleteRequest(id) {
        var options = {url: $deleteUrl + id, format: 'json'};
        Sys.UI.DomElement.removeCssClass($get("progressBar"), "off");  
        
        var data = Sys.Serialization.JavaScriptSerializer.serialize(id);      
	    new HttpHelper.AjaxAction().invoke(options, data, onPostCompleted);        
    }
    
    function onPostCompleted(executor, eventArgs) {
        if (executor.get_responseAvailable() && executor.get_statusCode() === 200)
        {
            grid.refresh();            
        } else { 
            alert('The application is not available. Try again later.');
        }        
        Sys.UI.DomElement.addCssClass($get("progressBar"), "off");        
    }
    
    function caretaker_onChange(undoCount, redoCount) {
		
	}

	function caretaker_onUndoRedo(cmd) {
		// TODO
	}

	function undo() {
		caretaker.undo();
	}

	function redo() {
		caretaker.redo();
	}

    function getStyle(oElm, strCssRule){
	    var strValue = "";
	    if(document.defaultView && document.defaultView.getComputedStyle){		    
		    strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	    }
	    else if(oElm.currentStyle){	    
		    strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			    return p1.toUpperCase();
		    });		    
		    strValue = oElm.currentStyle[strCssRule];
	    }
	    return strValue;
    }
    
    function gridRowRendered(e) {
	    // get status to set background color depending on status
	    var data = e.event_data.data;
		var tr = grid.getRows()[data.rowIndex];
	    var cssClass = null;
	    for( var i=0;i<$fieldOptions.status.length;i++) {
		    if ($fieldOptions.status[i].value == data.dataItem.Status) {
		        cssClass = $fieldOptions.status[i].text.toLowerCase();
			}	
        }
        // trick to set the style attribute explicitly so pasting 
		// on outlook keeps the color
		if (cssClass) {
		    for(var i=0; i<tr.childNodes.length; i++) {
                // TODO: it would be nice to replace the following with getStyle(element, 'background-color')
                //       so we keep all the style in css, but getStyle does not seems to work in IE (it works on FF)
                Sys.UI.DomElement.addCssClass(tr.childNodes[i], cssClass);
                setFixedStyles(tr.childNodes[i]);
            }
        }
	}
	
	function setFixedStyles(td) {
	    td.style.backgroundColor = getStyle(td, 'background-color');			    
        td.style.borderColor = getStyle(td, 'border-color');
        td.style.borderWidth = getStyle(td, 'border-width');
        td.style.borderStyle = getStyle(td, 'border-style');
        td.style.textAlign = getStyle(td, 'text-align');
	}
	
	function gridEditCommit(e) {
		// DataGridRowEditCommand(grid, gridRow, dataItem, oldValues, newValues)
		var eData = e.event_data.data;
		eData.dataItem.changed = true;
		var cmd = new DataGridRowEditCommand(e.event_data.event_target, eData.dataItem, eData.rowIndex, eData.oldValues, eData.newValues);
		caretaker.pushCommand( cmd );
		cmd.commit();
	}

    function gridCommand(e) {
       
	}